package controller;


import config.Interceptor.PassToken;
import entity.TokenDao;
import entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import service.impl.UserdeblisServiceimpl;
import service.impl.Userserviceimpl;
import utils.CommonRetumType;
import utils.JwtUtils;
import utils.RedisUtil;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

@RestController
@RequestMapping("/user")
@CrossOrigin
@Component
public class loginController {
    @Resource
    Userserviceimpl userserviceimpl;

    @Resource
    UserdeblisServiceimpl userdeblisServiceimpl;
    @Resource
    RedisUtil redisUtil;

    @PassToken
    @PostMapping("/login")
    public CommonRetumType login(@RequestParam("username") String username,
                                 @RequestParam("password") String password)
    {
        HashMap<String,String> site= new HashMap<String,String>();
        User user1 = userserviceimpl.login(username, password);
        String token = JwtUtils.createToken(user1.getId().toString(),user1.getRoleId().toString(),user1.getUsername(),password);

        TokenDao tokenDao = new TokenDao();
        tokenDao.setToken(token);
        redisUtil.set("token",token);
        redisUtil.set("userdebils",userdeblisServiceimpl.selectByPrimaryKey(user1.getId()));
        site.put("token",token);
        site.put("roleid",user1.getRoleId().toString());
        return CommonRetumType.create(site,"登录成功");
    }

    @PassToken
    @PostMapping("/register")
    public CommonRetumType register(@RequestParam(value="username",required = true) String username,
                                    @RequestParam(value="password",required = true) String password,
                                    @RequestParam(value = "roleid",required = true) int roleId)
    {
        if (userserviceimpl.register(username)!=null)
        {
            return CommonRetumType.create(null,"用户已存在，注册失败");
        }
        String newpassword = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        User user = new User();
        user.setUsername(username);
        user.setPassword(newpassword);
        user.setRoleId(roleId);

        int code = userserviceimpl.insertSelective(user);

        return  CommonRetumType.create(code,"注册成功");
    }
}
